import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { renderRoutes } from "react-router-config";
import { DownOutlined, HomeOutlined, UpOutlined } from '@ant-design/icons';
import { PrivilegeButton, SystemNav } from "tiklab-privilege-ui";
import './sysMana.scss';
import { getUser, getVersionInfo } from "tiklab-core-ui";
import IconCommon from "../../common/IconCommon";
import { useLocation } from "react-router";
import ExtensionCommon from "../../common/ExtensionCommon/ExtensionCommon";

// 常量提取到组件外部
const SPECIAL_KEYS = [
    "/setting/orga",
    "/setting/user",
    "/setting/dir",
    "/setting/userGroup",
];

const OPEN_NEW_WINDOW_URLS = [
    "/openapi/doc",
];

const PREMIUM_FEATURES = [
    '/setting/logo',
    '/setting/whitelist'
];

const SysManage = (props) => {
    const { settingMenu, route, history } = props;
    const routers = route.routes;

    const [selectKey, setSelectKey] = useState();
    const [menuRouter, setMenuRouter] = useState([]);
    const [expandedTree, setExpandedTree] = useState([]);

    // 使用 useMemo 缓存版本信息
    const versionInfo = useMemo(() => getVersionInfo(), []);

    // 缓存 authConfig
    const authConfig = useMemo(() => JSON.parse(localStorage.getItem('authConfig') || '{}'), []);

    // 使用 useLocation 获取当前路径
    const { pathname } = useLocation();

    // 设置菜单数据
    useEffect(() => {
        setMenuRouter(settingMenu);
    }, [settingMenu]);

    // 设置选中的菜单项
    useEffect(() => {
        if (pathname.startsWith("/setting")) {
            setSelectKey(pathname);
        }
    }, [pathname]);

    // 检查节点是否展开
    const isExpandedTree = useCallback((key) => {
        return expandedTree.includes(key);
    }, [expandedTree]);

    // 切换节点展开状态
    const toggleExpand = useCallback((key) => {
        setExpandedTree(prev =>
            prev.includes(key) ? prev.filter(item => item !== key) : [...prev, key]
        );
    }, []);

    // 处理菜单选择
    const handleSelect = useCallback((key) => {
        // 处理特殊键，需要在新窗口中打开
        if (!authConfig.authType && SPECIAL_KEYS.includes(key)) {
            const authServiceUrl = authConfig.authServiceUrl;
            const ticket = getUser().ticket;
            const url = `${authServiceUrl}#${key}?ticket=${ticket}`;
            window.open(url, '_blank');
            return;
        }

        // 处理需要在新窗口打开的 URL
        if (OPEN_NEW_WINDOW_URLS.includes(key)) {
            window.open(`#${key}`, '_blank');
            return;
        }

        // 处理高级功能限制
        if (versionInfo.expired && PREMIUM_FEATURES.includes(key)) {
            return; // 许可证过期且是高级功能，不执行跳转
        }

        // 正常导航
        setSelectKey(key);
        history.push(key);
    }, [authConfig, history, versionInfo.expired]);

    // 渲染菜单项
    const renderMenu = useCallback((data, deep, isFirst) => (
        <PrivilegeButton key={data.id} code={data.purviewCode || ''}>
            <li
                className={`orga-aside-li ${data.id === selectKey ? 'orga-aside-select' : ''}`}
                onClick={() => handleSelect(data.id)}
                style={{ paddingLeft: isFirst ? "0px" : "25px" }}
            >
                {data.extension && versionInfo.expired ? (
                    <div style={{ padding: "0 15px 0 16px" }}>
                        <ExtensionCommon
                            name={data.title}
                            history={history}
                            id={data.id}
                        />
                    </div>
                ) : (
                    <div className='aside-li'>
                        {isFirst && <IconCommon icon={data.icon} className="icon-m" />}
                        {data.title}
                        {!authConfig.authType && SPECIAL_KEYS.includes(data.id) && (
                            <IconCommon icon="dakaixinyemian" className="icon-s" />
                        )}
                        {OPEN_NEW_WINDOW_URLS.includes(data.id) && (
                            <IconCommon icon="dakaixinyemian" className="icon-s" />
                        )}
                    </div>
                )}
            </li>
        </PrivilegeButton>
    ), [handleSelect, selectKey, authConfig, versionInfo.expired, history]);

    // 渲染子菜单
    const renderSubMenu = useCallback(({ title, id, children, purviewCode, icon }, deep) => (
        <PrivilegeButton key={id} code={purviewCode || ''}>
            <li>
                <div
                    className="orga-aside-item aside-li"
                    onClick={() => toggleExpand(id)}
                    style={{ paddingLeft: "16px" }}
                >
                    <div className="menu-name-icon">
                        <IconCommon icon={icon} className="icon-m" />
                        <span>{title}</span>
                    </div>
                    {children && children.length > 0 && (
                        isExpandedTree(id)
                            ? <DownOutlined style={{ fontSize: '10px' }} />
                            : <UpOutlined style={{ fontSize: '10px' }} />
                    )}
                </div>
                {children && children.length > 0 && (
                    <ul className={`orga-aside-ul ${isExpandedTree(id) ? '' : 'orga-aside-hidden'}`}>
                        {children.map(item =>
                            item.children && item.children.length > 0
                                ? renderSubMenu(item, deep + 1)
                                : renderMenu(item, deep + 1, false)
                        )}
                    </ul>
                )}
            </li>
        </PrivilegeButton>
    ), [isExpandedTree, toggleExpand, renderMenu]);

    // 渲染菜单列表
    const showUlView = useCallback((data) => (
        data.map(item =>
            item.children && item.children.length > 0
                ? renderSubMenu(item, 1)
                : renderMenu(item, 1, true)
        )
    ), [renderMenu, renderSubMenu]);

    // 处理返回首页
    const handleBackToHome = useCallback(() => {
        localStorage.setItem("leftRouter", "/index");
        history.push("/index");
    }, [history]);

    return (
        <SystemNav
            {...props}
            applicationRouters={menuRouter}
            outerPath="/setting"
            noAccessPath="/noaccess"
            expandedTree={expandedTree}
            setExpandedTree={setExpandedTree}
        >
            <div className='sysmana-layout'>
                <div className="tiklab-orga-aside">
                    <div className="system-header">
                        <div
                            className="system-header-title system-header-item"
                            onClick={() => history.push("/setting/home")}
                        >
                            设置
                        </div>
                        <div
                            className="system-header-back-home system-header-item"
                            onClick={handleBackToHome}
                        >
                            <HomeOutlined style={{ fontSize: '18px', cursor: 'pointer' }} />
                            返回首页
                        </div>
                    </div>
                    <ul style={{ padding: 0 }}>
                        {showUlView(menuRouter)}
                    </ul>
                </div>
                <div className='sysmana-content'>
                    {renderRoutes(routers)}
                </div>
            </div>
        </SystemNav>
    );
};

export default SysManage;